package cc.sunwl.study.java8.OptionalAPI;

import java.util.Optional;
import java.util.Properties;

public class OptionalTest {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("a", "5");
        props.setProperty("b", "true");
        props.setProperty("c", "-1");
        System.out.println("a = " + readDuration(props, "a"));
        System.out.println("b = " + readDuration(props, "b"));
        System.out.println("c = " + readDuration(props, "c"));
    }

    private static int readDuration(Properties props, String name) {
        return Optional//
                .ofNullable(props.getProperty(name))//
                .flatMap(OptionalTest::stringToInt)//
                .filter(e -> e > 0)//
                .orElse(0);
    }

    /**
     * 不推荐使用OptionalInt基础类型的，因为不支持map、flatMap以及filter方法，与Stream正好相反
     *
     * @param s 待转换的字符串
     * @return 转换成功返回int，否则返回Optional.empty()
     */
    private static Optional<Integer> stringToInt(String s) {
        try {
            return Optional.of(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }
}
